package com.csnf.hymall.servlet;

import com.alibaba.fastjson.JSONObject;
import com.csnf.hymall.service.ProductOrderService;
import com.csnf.hymall.service.ProductService;
import com.csnf.hymall.service.UserService;
import com.csnf.hymall.service.impl.ProductOrderServiceImpl;
import com.csnf.hymall.service.impl.ProductServiceImp;
import com.csnf.hymall.service.impl.UserServiceImpl;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@WebServlet("/admin/home")
public class AdminHomeServlet extends BaseServlet {
    @Override
    protected void doService(HttpServletRequest req, HttpServletResponse resp) {
        try {
            switch (action) {
                case "goHome":
                    goHome(req, resp);
                    break;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private ProductService productService = new ProductServiceImp();
    private UserService userService = new UserServiceImpl();
    private ProductOrderService productOrderService = new ProductOrderServiceImpl();

    public void goHome(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object adminId = checkAdmin(session);//查询session判断用户是否存在
        if (adminId == null) {
            req.getRequestDispatcher("/page/admin/loginPage.jsp").forward(req, resp);//跳转到登录页面
        }

        String startDate = req.getParameter("startDate"); //获取开始时间
        String endDate = req.getParameter("endDate");// 获取结束时间
        Integer productTotal = productService.getTotalByDate(startDate, endDate);
        Integer userTotal = userService.getUserTotal(startDate, endDate);
        Integer orderTotal = productOrderService.getOrderTotal(startDate, endDate,3);
        String method = req.getMethod().toUpperCase();//请求方式 ，并转换为大写
        if (method.equals("GET")) {//get 表示从 登录 跳转过来的
            req.setAttribute("productTotal", productTotal);
            req.setAttribute("userTotal", userTotal);
            req.setAttribute("orderTotal", orderTotal);
            //使用request转发
            req.getRequestDispatcher("/page/admin/homePage.jsp").forward(req,resp);
        }else if (method.equals("POST")) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("productTotal", productTotal);
            jsonObject.put("userTotal", userTotal);
            jsonObject.put("orderTotal", orderTotal);
            //设置response 响应的数据流类型
            resp.setContentType("application/json;charset=utf-8");
            //使用PrintWriter 返回json 字符串到前端页面
            PrintWriter pw = resp.getWriter();//获取相应输出流
            pw.print(jsonObject.toJSONString());
            pw.flush();//刷新输出
            pw.close();//关闭输出
        }

    }

}